package com.gary.mongo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author peng_rui
 * @date 2022/6/13
 */
@Slf4j
@Component
public class KongUtils {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${add.kong.service:{\"name\": \"test-service\",\"protocol\": \"http\",\"host\": \"example.com\",\"port\": 9701}}")
    public String addServiceJson;
    @Value("${del.kong.service.name:test-service}")
    public String delServiceName;
    public static final String POST_GET_SERVICE_URL = "http://%s/services";
    public static final String DELETE_SERVICE_URL = "http://%s/services/%s";

    public boolean detectKongUsability(String addr) {
        try {
            String postGetUrl = String.format(POST_GET_SERVICE_URL, addr);
            String delUrl = String.format(DELETE_SERVICE_URL, addr, delServiceName);
            //新增service
            log.info("add kong service : {}", addServiceJson);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> entity = new HttpEntity<>(addServiceJson, headers);
            ResponseEntity<String> addResp = restTemplate.exchange(postGetUrl, HttpMethod.POST, entity, String.class);
            log.info("addResp : {}", addResp.getBody());
            if (!addResp.getStatusCode().is2xxSuccessful()) {
                log.error("kong 新增 service 探测失败");
                return false;
            }
            Thread.sleep(500L);
            //查询service
            log.info("search kong services");
            ResponseEntity<String> searchResp = restTemplate.exchange(postGetUrl, HttpMethod.GET, null, String.class);
            log.info("searchResp : {}", searchResp.getBody());
            if (!searchResp.getStatusCode().is2xxSuccessful()) {
                log.error("kong 查询 services 探测失败");
                return false;
            }
            //删除
            log.info("del kong service : {}", delServiceName);
            ResponseEntity<String> delResp = restTemplate.exchange(delUrl, HttpMethod.DELETE, null, String.class);
            log.info("delResp : {}", delResp.getBody());
            if (!delResp.getStatusCode().is2xxSuccessful()) {
                log.error("kong 删除 service 探测失败");
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("kong 健康状态探测失败", e);
            return false;
        }
    }
}
